﻿using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using DevelopmentKit.Domain;
using DevelopmentKit.Enums;
using DevelopmentKit.Extensions.SharpArch.DataContext;
using LERP.Web.Controllers.ViewModels.AccountViewModels;

namespace DevelopmentKit.Web.Controllers
{
    public class AccountController : Controller
    {
        private readonly IDataContext _query;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="query"></param>
        public AccountController(IDataContext query)
        {
            _query = query;
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        } 

        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var user = _query.FindAll<User>().FirstOrDefault(m => m.UserName == model.UserName && m.Status == UserStatus.Normal);
                    if (null != user && FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "MD5") == user.Password)
                    {
                        FormsAuthentication.SetAuthCookie(user.Id.ToString(CultureInfo.InvariantCulture), true);
                        if (!string.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        return RedirectToAction("Index", "Home");
                    } 
                    ModelState.AddModelError("", "用户不存在或者密码错误.");

                } 
                // If we got this far, something failed, redisplay form
                return View(model);
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
                return View();
            }
        }

       [HttpGet]
        public ActionResult Logoff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }
         
    }
}
